﻿using UnityEngine;
using System.Collections;

public class ImageFile : MonoBehaviour {
	public BaseFile BaseFileInfo;
	public GameObject VisualRoot;
	public GameObject VisualObj;
	public Texture2D t2D_MainTexture;
	public Texture2D t2D_Icon;
	public Texture2D t2D_DefaultImageTexture;
	public bool b_MakeIconOnLoad;
	public bool b_ShouldResize;
	public bool b_LoadingImage;
	public bool b_HasFullImage;
	public bool b_HasIcon;
	public float f_RealWidth;
	public float f_RealHeight;
	
	void Start(){
		b_HasIcon = false;
		b_HasFullImage = false;
		b_ShouldResize = true;
		if(b_MakeIconOnLoad){
			StartCoroutine(LoadImage());
		}
		Setup(); 
	}
	public void Setup(){
		//print("->"+this.transform.name+" Ready.");
		b_LoadingImage = false;
		f_RealWidth = 0;
		f_RealHeight = 0;
		if(b_HasIcon){
			t2D_MainTexture = t2D_Icon;
		}
		else{
			t2D_MainTexture = t2D_DefaultImageTexture;
		}
		ApplyTexture(t2D_MainTexture);
		if(b_HasFullImage){
			ForceEmptyUsedMem();
		}
		VisualRoot.transform.rotation = Quaternion.Euler(new Vector3(0,0,0));
	}
	public void ForceEmptyUsedMem(){
		System.GC.Collect();
		Resources.UnloadUnusedAssets();
	}
	public void Refresh(){
		if(!b_LoadingImage){
			if(!b_HasIcon){
				StartCoroutine(LoadImage());
			}
		}
		//     rotation                =                                                pos - pos of thing to look at = angles we want
		VisualRoot.transform.rotation = Quaternion.LookRotation(	VisualRoot.transform.position - Camera.main.transform.position ,	Camera.main.transform.up);
	}
	public void LoadFullImage(){
		if(!b_LoadingImage){
			b_ShouldResize = false;
			StartCoroutine(LoadImage());
		}
	}
	void ApplyTexture(Texture2D NewTexture){
		t2D_MainTexture = NewTexture;
		VisualObj.renderer.material.mainTexture = t2D_MainTexture;
	}
	public IEnumerator LoadImage(){
		b_LoadingImage = true;
		//print("Loading:"+BaseFileInfo.FullPath);
		WWW www = new WWW("file://"+BaseFileInfo.FullPath);
		yield return www;
		f_RealWidth = www.texture.width;
		f_RealHeight = www.texture.height;
		Texture2D LoadedTexture = new Texture2D(4,4);
		www.LoadImageIntoTexture(LoadedTexture);
		if(b_ShouldResize){
			TextureScale.Bilinear(LoadedTexture,32,32);
			t2D_Icon = LoadedTexture;
			b_HasIcon = true;
			ForceEmptyUsedMem();
			b_ShouldResize = false;
		}
		else{
			b_HasFullImage = true;
		}
		ApplyTexture(LoadedTexture);
		ForceEmptyUsedMem();
		b_LoadingImage = false;
	}


}
